<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'accept:pre:pmPreacceptance:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rectList>
        <a-button
          class="mt-2"
          @click="handlePmRectificationAdd"
          v-auth="'accept:pre:pmPreacceptance:edit'"
          v-if="record.isNewRecord"
          style="margin-bottom: 10px"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('添加整改项') }}
        </a-button>
        <BasicTable
          @register="registerPmRectificationTable"
          @row-click="handlePmRectificationRowClick"
        >
          <template #rectListUpload="{ record: childRecord }">
            <BasicUpload
              v-model:value="childRecord.dataMap"
              :bizKey="childRecord.id"
              :bizType="'rectList_file'"
              :uploadType="'all'"
              :loadTime="record.__t"
              :isPreview="false"
              :disabled="!record.isNewRecord"
            />
          </template>
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsAcceptPrePmPreacceptanceForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicUpload } from '/@/components/Upload';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmPreacceptance,
    pmPreacceptanceSave,
    pmPreacceptanceForm,
  } from '/@/api/accept/pre/pmPreacceptance';
  import { pmProjectinformationPreTreeData } from '/@/api/proj/info/pmProjectinformation';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('accept.pre.pmPreacceptance');
  const { showMessage } = useMessage();
  const record = ref<PmPreacceptance>({} as PmPreacceptance);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('发起预验收') : t('编辑预验收'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('项目名称'),
      field: 'projectno',
      fieldLabel: 'projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationPreTreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
        disabled: computed(() => !record.value.isNewRecord),
      },
      required: true,
    },
    {
      label: t('项目编号'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        // readonly: true,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('验收方式'),
      field: 'canfilecheck',
      component: 'Select',
      componentProps: {
        dictType: 'zf_ys_type',
        allowClear: true,
        disabled: computed(() => !record.value.isNewRecord),
      },
      required: true,
    },
    {
      label: t('参与人名称'),
      field: 'usercodepre',
      fieldLabel: 'usernamepre',
      component: 'ListSelect',
      componentProps: {
        checkbox: true,
        selectType: 'empUserSelect',
        disabled: computed(() => !record.value.isNewRecord),
      },
    },
    {
      label: t('验收图片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmPreAcceptance_image',
        uploadType: 'image',
        isPreview: true,
        // maxNumber: 3,
        // minNumber: 3,
        disabled: computed(() => !record.value.isNewRecord),
      },
      // rules: [
      //   { required: true },
      //   {
      //     validator(_rule, value) {
      //       return new Promise((resolve, reject) => {
      //         const len = !value || value['PmPreAcceptance_image__len'] || 0;
      //         if (len != 3) reject(t('请上传3张验收图片'));
      //         else resolve();
      //       });
      //     },
      //   },
      // ],
       rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['PmPreAcceptance_image__len'] || 0;
              if (len == 0) reject(t('请上传图片'));
              else resolve();
            });
          },
        },
      ],
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('发起人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('发起时间'),
      field: 'createDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        disabled: true,
      },
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('整改明细'),
      field: 'pmRectificationList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rectList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerPmRectificationTable, pmRectificationTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmRectificationDelete.bind(this, record1),
          },
          auth: 'accept:pre:pmPreacceptance:edit',
          ifShow: record.value.isNewRecord,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmRectificationTableData(_res: Recordable) {
    pmRectificationTable.setColumns([
      {
        title: t('整改方式'),
        dataIndex: 'rectificationmeasures',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('整改项'),
        dataIndex: 'rectificationcontent',
        width: 250,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('整改期限'),
        dataIndex: 'endtime',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: false,
      },
      {
        title: t('图片'),
        dataIndex: 'upload',
        width: 120,
        align: 'left',
        slot: 'rectListUpload',
      },
    ]);
    pmRectificationTable.setTableData(record.value.pmRectificationList || []);
  }

  function handlePmRectificationRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmRectificationAdd() {
    pmRectificationTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      rectificationmeasures: '现场整改',
    });
  }

  function handlePmRectificationDelete(record: Recordable) {
    pmRectificationTable.deleteTableDataRecord(record);
  }

  async function getPmRectificationList() {
    let pmRectificationListValid = true;
    let pmRectificationList: Recordable[] = [];
    for (const record of pmRectificationTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmRectificationListValid = false;
      }
      pmRectificationList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmRectificationTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmRectificationList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmRectificationListValid) {
      throw { errorFields: [{ name: ['pmRectificationList'] }] };
    }
    return pmRectificationList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmPreacceptanceForm(data);
    record.value = (res.pmPreacceptance || {}) as PmPreacceptance;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setPmRectificationTableData(res);
    setDrawerProps({ loading: false });
    setDrawerProps({ showOkBtn: record.value.status == 0 ? false : true });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.pmRectificationList = await getPmRectificationList();
      // console.log('submit', params, data, record);
      const res = await pmPreacceptanceSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
